//
//  WorkflowListViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 2017/8/28.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "WorkflowListViewController.h"
#import "JTCalendar.h"
#import "WorkflowListCell.h"
#import "WorkflowDetailViewController.h"
#import "CalendarHeaderCell.h"
#import "CalendarCell.h"

NSString *const WorkflowListViewControllerCodeParametersParamKey = @"WorkflowListViewControllerCodeParametersParamKey";

@interface WorkflowListViewController ()<CalendarCellDelegate>
{
    NSDate *_todayDate;
    NSDate *_dateSelected;
    NSString *_code;
    NSMutableArray *_eventData;
    
    NSMutableArray *_datas;
    RSWDataOperation *_manager;
}
@end

@implementation WorkflowListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    [self setBackNavigateItemTitle:@"全部事件"];
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    [self initVariable];
    [self initUI];
    
    [self reloadData:@"getList"];
}

-(void)initVariable
{
    [self setBackNavigateItemTitle:@""];
    
    _code = @"";
    if(self.param[WorkflowListViewControllerCodeParametersParamKey] != nil)
        _code = self.param[WorkflowListViewControllerCodeParametersParamKey];
    
    _dateSelected = [NSDate date];
    _todayDate = [NSDate date];
    _eventData = [NSMutableArray new];
    
    _datas = [NSMutableArray new];
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    [self addMainThreadObserverWithDictionarySelector:
     @{    RSWDataOperationWorkflowProcessNextNotification:
               @"observerRSWDataOperationWorkflowProcessNextNotification:"
           }];
}

-(void)initUI
{
    [self createTableView:XUITabelViewStyleTypePlain];
    _ctable.separatorExistFollowCell = NO;
    
    CGFloat top = [XUINavigationController navigationController].navigationBar.bottom;
    self.adjustTableViewInset = UIEdgeInsetsMake(top, 0,([UIDevice is58InchScreen]?83:49), 0);
    
    _ctable.tableFooterView = [[UIView alloc] init];
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [_manager terminateRequest];
    [self removeObserver];
}

#pragma --mark private method
-(void)reloadData:(NSString*)funcationName
{
    [_manager getAllWorkflowDate:[_dateSelected toStringDate:yMd] pageIndex:1 pageSize:5000 code:_code completion:^(NSInteger nResult, XMSQueueDictionary *dic, NSError *error) {
        [self requestComplete:nil funcationName:funcationName result:nResult output:dic error:error];
    }];
}

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    if([szFuncationname isEqualToString:@"getList"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     [_datas removeAllObjects];
                     
                     if([output isKindOfClass:[XMSQueueDictionary class]])
                     {
                         XMSQueueDictionary *dic = output;
                         
                         NSArray *ar = [dic getValueForKey:@"List"];
                         NSArray *arr = [WorkflowCellList workflowListToListArray:ar];
                         if(arr.count > 0)
                         {
                             [_datas addObjectsFromArray:arr];
                         }
                         
                         ar = [dic getValueForKey:@"DateList"];
                         if(ar.count > 0)
                         {
                             [_eventData addObjectsFromArray:ar];
                         }
                         
                         [_ctable reloadData];
                     }
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据请求失败"];
                     break;
                 }
             }
         }];
    }
}

#pragma mark --
#pragma mark -- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WorkflowCellList * l = _datas[indexPath.row];
    if(l.rowHeight <= CaleRowHeightTag)
    {
        switch(l.type)
        {
            case WorkflowListTypeDateType:
            {
                l.rowHeight = [CalendarHeaderCell caleHeight];
                break;
            }
            case WorkflowListTypeCalendarType:
            {
                l.rowHeight = [CalendarCell caleHeight];
                break;
            }
            case WorkflowListTypeContent:
            {
                l.rowHeight = [WorkflowListCell caleHeight:tableView.width content:l.wf.appName];
                break;
            }
            default:
            {
                break;
            }
        }
    }
    return l.rowHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datas.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WorkflowCellList * l = _datas[indexPath.row];
    switch(l.type)
    {
        case WorkflowListTypeDateType:
        {
            CalendarHeaderCell *cell = [[CalendarHeaderCell alloc]initWithReuseIdentifier:@"CalendarHeaderCell"];
            
            [cell setDate:_dateSelected];
            cell.szTag = @"1";
            return cell;
            break;
        }
        case WorkflowListTypeCalendarType:
        {
            CalendarCell *cell = [[CalendarCell alloc]initWithReuseIdentifier:@"CalendarCell"];
            [cell setDate:_dateSelected];
            [cell createDateEvents:[_eventData fetchArrayObjectPorpertyValueWithPorperty:@"createdDateTime"] downArr:nil];
            cell.delegate = self;
            
            cell.szTag = @"2";
            return cell;
            break;
        }
        case WorkflowListTypeContent:
        {
            WorkflowListCell *cell = [[WorkflowListCell alloc] initWithReuseIdentifier:@"WorkflowListCell"];
            
            WorkflowToDoListInfo * info = l.wf;
            cell.szTag = info.appInstanceID;
            cell.processName = info.processName;
            cell.processState = [cell setProcessStatus:[info.processState intValue]];
            cell.appName = info.appName;
            cell.createdUserDept = [NSString stringWithFormat:@"%@(%@)",info.createdByUserName,info.createdByDept];
            cell.createdDateTime = info.createdDateTime;
            
            cell.szTag = @"3";
            return cell;
            break;
        }
        default:
        {
            break;
        }
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [UIViewController closeKeyBoard];
    
    WorkflowCellList * l = _datas[indexPath.row];
    WorkflowToDoListInfo * info = l.wf;
    if(info != nil)
    {
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        
        NSDictionary *dic = @{
                              ProcessName:info.processName,
                              ProcessCode:info.processCode,
                              InstanceId:info.appInstanceID,
                              CustomForm:info.customFormID,
                              Version:info.version
                              };
        
        p.param[WorkflowDetailViewControllerListDicDataParametersParamKey] = dic;
        
        [XUINavigationController pushViewControllerClass:[WorkflowDetailViewController class] withSwitchParam:p];
    }
}

#pragma ---mark CalendarCellDelegate
-(void)didTouchDayView:(CalendarCell*)calendarCell dateSelected:(NSDate*)dateSelected
{
    _dateSelected = dateSelected;
    [self reloadData:@"getList"];
}

-(void)calendarDidLoadPreviousPage:(CalendarCell*)calendarCell dateSelected:(NSDate*)dateSelected
{
    _dateSelected = dateSelected;
    [self reloadData:@"getList"];
}

-(void)calendarDidLoadNextPage:(CalendarCell*)calendarCell dateSelected:(NSDate*)dateSelected
{
    _dateSelected = dateSelected;
    [self reloadData:@"getList"];
}

#pragma mark --
#pragma mark -- observer

-(void)observerRSWDataOperationWorkflowProcessNextNotification:(NSNotification*)noti
{
    [self reloadData:@"getList"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

